package o5bracket;

import java.util.Stack;

/**
 * @author shkstart
 * @create 2021-12-29-15:33
 */
/*
*
* 判断输入的括号能否成功匹配
*
* */
public class Bracket {

    public static void main(String[] args) {
        String s = "}";
        boolean valid = isValid(s);
        System.out.println(valid);
    }

    public static boolean isValid(String s) {
        Stack<String> stack = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '{' || s.charAt(i) == '('|| s.charAt(i) == '[') {
                if (i == s.length() - 1) {
                    return false;
                }
                stack.push(s.charAt(i)+"");
            } else {
                try {
                    if (s.charAt(i) == '}' && stack.peek().equals("{")) {
                        stack.pop();
                    } else if (s.charAt(i) == ')' && stack.peek().equals("(")) {
                        stack.pop();
                    } else if (s.charAt(i) == ']' && stack.peek().equals("[")) {
                        stack.pop();
                    } else {
                        return false;
                    }
                } catch (Exception e) {
                    return false;
                }

            }
        }
        if (stack.isEmpty()) {
            return true;
        }
        return false;
    }

}
